<template>
  <div class="user-management-container">
    <!-- 页面标题和面包屑 -->
    <div class="page-header">
      <h2>用户管理</h2>

    </div>

    <!-- 主内容卡片 -->
    <el-card class="user-management-card">
      <!-- 卡片顶部操作区 -->
      <div class="card-header flex items-center justify-end gap-4">
        <div class="header-info" >
          <h3 class="section-title">用户列表</h3>
          <p class="section-description">管理系统中的所有用户账户</p>
        </div>
        <div>
        <el-button
          type="primary"
          class="add-user-btn"
          @click="handleAddUser"
          :icon="Plus"
        >
          添加用户
        </el-button>
        <el-button
          type="success"
          class="export-excel-btn"
          @click="handleExportExcel"
          :icon="Download"
        >
          导出Excel
        </el-button>
      </div>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="search-filter">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名或邮箱"
          prefix-icon="Search"
          clearable
          class="search-input"
          style="width: 300px"
        />
        <el-select
          v-model="roleFilter"
          placeholder="筛选角色"
          clearable
          class="role-filter"
          style="width: 150px"
        >
          <el-option label="全部" value="" />
          <el-option label="管理员" value="ROLE_ADMIN" />
          <el-option label="普通用户" value="ROLE_USER" />
        </el-select>
      </div>

      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="filteredUsers"
        style="width: 100%"
        class="user-table"
        border="false"
        highlight-current-row
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          fixed
          align="center"
        />
        <el-table-column prop="username" label="用户名" min-width="150" align="left">
          <template #default="scope">
            <div class="user-info">
              <div class="user-avatar-small">
                {{ scope.row.username.charAt(0).toUpperCase() }}
              </div>
              <span class="user-name">{{ scope.row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="200" align="left" />
        <el-table-column prop="firstName" label="姓氏" align="left"></el-table-column>
        <el-table-column prop="lastName" label="名字" align="left"></el-table-column>
        <el-table-column prop="roles" label="角色" width="120" align="left">
          <template #default="scope">
            <el-tag
              v-for="role in scope.row.roles"
              :key="role.name"
              :type="role.name === 'ROLE_ADMIN' ? 'primary' : 'success'"
              class="role-tag"
            >
              {{ role.name === 'ROLE_ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEditUser(scope.row)"
              :disabled="isCurrentUser(scope.row)"
              class="operation-btn"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteUser(scope.row)"
              :disabled="isCurrentUser(scope.row)"
              class="operation-btn"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          共 <span class="highlight-text">{{ filteredUsers.length }}</span> 条记录
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          layout="prev, pager, next, jumper, sizes"
          :total="filteredUsers.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 50, 100]"
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :before-close="handleCloseDialog"
      class="user-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="formRules"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            class="form-input"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入邮箱"
            class="form-input"
          />
        </el-form-item>
        <el-form-item label="密码" :required="!editingUserId">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码" 
            show-password
            class="form-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input v-model="userForm.firstName" placeholder="姓氏" class="form-input"></el-input>
            </el-col>
            <el-col :span="12">
              <el-input v-model="userForm.lastName" placeholder="名字" class="form-input"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <!-- 使用selectedRoles字符串数组来绑定checkbox-group -->
          <el-checkbox-group v-model="selectedRoles">
            <el-checkbox label="ROLE_USER" class="form-checkbox">普通用户</el-checkbox>
            <el-checkbox label="ROLE_ADMIN" class="form-checkbox">管理员</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleSaveUser" class="confirm-btn">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElTag, ElCheckbox, ElCheckboxGroup } from 'element-plus'
import { Plus, Edit, Delete, Download } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { User, RegisterRequest, Role } from '../types/user'
import authService from '../services/auth.service'

// 表格相关数据
const loading = ref(false)
const users = ref<User[]>([])
const searchQuery = ref('')
const roleFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框相关数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const editingUserId = ref<number | null>(null)
const userFormRef = ref<FormInstance>();
const userForm = ref<Partial<User & RegisterRequest>>({
  username: '',
  email: '',
  password: '',
  firstName: '',
  lastName: '',
  roles: [] as Role[]
})

// 用于checkbox-group的角色字符串数组
const selectedRoles = ref<string[]>(['ROLE_USER'])

// 当userForm.roles变化时，同步更新selectedRoles
watch(() => userForm.value.roles, (newRoles: Role[] | undefined) => {
  if (newRoles && Array.isArray(newRoles)) {
    selectedRoles.value = newRoles.map(role => role.name);
  } else {
    selectedRoles.value = [];
  }
}, { deep: true })

// 当selectedRoles变化时，同步更新userForm.roles
watch(selectedRoles, (newRoleNames: string[]) => {
  userForm.value.roles = newRoleNames.map((name: string) => ({ id: 0, name })) as Role[];
}, { deep: true })

// 表单验证规则
const formRules = ref<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' },
    {
      type: 'array',
      min: 1,
      message: '至少选择一个角色',
      trigger: 'change'
    }
  ]
})

// 计算过滤后的用户列表
const filteredUsers = computed(() => {
  let result = [...users.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(user => 
      user.username.toLowerCase().includes(query) || 
      user.email.toLowerCase().includes(query)
    )
  }
  
  // 角色过滤
  if (roleFilter.value) {
    result = result.filter(user => 
      user.roles.some(role => role.name === roleFilter.value)
    )
  }
  
  return result
})

// 检查是否是当前登录用户
const isCurrentUser = (user: User) => {
  const currentUser = authService.getCurrentUser()
  return currentUser && currentUser.id === user.id
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const data = await authService.getAllUsers()
    users.value = data
  } catch (error) {
    console.error('Failed to fetch users:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理添加用户
const handleAddUser = () => {
  dialogTitle.value = '添加用户'
  editingUserId.value = null
  resetForm()
  dialogVisible.value = true
}

// 处理编辑用户
const handleEditUser = (user: User) => {
  dialogTitle.value = '编辑用户'
  editingUserId.value = user.id
  userForm.value = {
    ...user,
    // 清除密码，编辑时可选修改
    password: ''
  }
  dialogVisible.value = true
}

  // 处理导出Excel
  const handleExportExcel = async () => {
    ElMessage({ message: '开始导出Excel文件...', type: 'info' });
    
    try {
      // 使用authService中的方法调用导出API，会自动添加认证token
      const blob = await authService.exportUsersToExcel(searchQuery.value, roleFilter.value);
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `用户列表_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.xlsx`;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // 释放URL对象
      window.URL.revokeObjectURL(url);
      
      // 显示导出成功消息
      ElMessage({ message: 'Excel文件导出成功', type: 'success' });
    } catch (error) {
      console.error('导出Excel失败:', error);
      ElMessage({ message: 'Excel文件导出失败，请重试', type: 'error' });
    }
  }
  
  // 处理删除用户
  const handleDeleteUser = async (user: User) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除用户 "${user.username}" 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      await authService.deleteUser(user.id)
      ElMessage.success('用户删除成功')
      fetchUsers() // 重新获取用户列表
    } catch (error) {
      // 用户取消删除时不会显示错误信息
      if (error !== 'cancel') {
        console.error('Failed to delete user:', error)
        ElMessage.error('用户删除失败')
      }
    }
  }
  
  // 处理保存用户
const handleSaveUser = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    if (editingUserId.value) {
      // 编辑用户
      // 使用Partial<User & RegisterRequest>类型来允许password属性
      const userData: Partial<User & RegisterRequest> = {
        ...userForm.value,
        id: editingUserId.value
      }
      // 如果密码为空，不更新密码
      if (!userData.password) {
        delete userData.password
      }
      // 转换角色格式确保正确类型
      if (userData.roles && Array.isArray(userData.roles)) {
        userData.roles = userData.roles.map((role: any) => {
          if (typeof role === 'string') {
            return { id: 0, name: role } as Role;
          } else if (role && typeof role === 'object') {
            // 确保角色对象有正确的结构
            return { id: role.id || 0, name: role.name };
          }
          return role;
        });
      }
      await authService.updateUser(editingUserId.value!, userData as User)
      ElMessage.success('用户更新成功')
    } else {
      // 添加用户
      // 转换角色格式
      const registerData = { ...userForm.value };
      if (registerData.roles && Array.isArray(registerData.roles)) {
        registerData.roles = registerData.roles.map((role: any) => {
          if (role && typeof role === 'object' && 'name' in role) {
            return role.name;
          }
          return role;
        });
      }
      await authService.register(registerData as RegisterRequest)
      ElMessage.success('用户添加成功')
    }
    
    dialogVisible.value = false
    fetchUsers() // 重新获取用户列表
  } catch (error: any) {
    console.error('Failed to save user:', error)
    ElMessage.error(
      error.response?.data?.message || error.message || '保存用户失败'
    )
  }
}

// 处理关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  userForm.value = {
    username: '',
    email: '',
    password: '',
    firstName: '',
    lastName: '',
    roles: [] as Role[]
  }
  // 重置selectedRoles
  selectedRoles.value = ['ROLE_USER']
}

// 表格行样式类名
const tableRowClassName = () => {
  return 'table-row'
}

// 分页相关处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
}

// 页面加载时获取用户列表
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
/* 主要颜色变量 */
:root {
  --primary-blue: #3498db;
  --primary-blue-light: #66b1ff;
  --primary-blue-dark: #2980b9;
  --primary-blue-ultralight: #e3f2fd;
  --text-primary: #2c3e50;
  --text-secondary: #7f8c8d;
  --background-light: #f8f9fa;
  --border-radius: 12px;
  --shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.user-management-container {
  width: 100%;
  margin: 0;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面标题和面包屑 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.page-header h2 {
  font-size: 2rem;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0;
}

.breadcrumb {
  font-size: 14px;
  color: var(--text-secondary);
}

.breadcrumb a {
  color: var(--primary-blue);
  text-decoration: none;
  transition: color 0.2s;
}

.breadcrumb a:hover {
  color: var(--primary-blue-dark);
}

/* 主内容卡片 */
.user-management-card {
  background: white;
  border-radius: var(--border-radius);
  box-shadow: var(--shadow);
  border: none;
  overflow: hidden;
}

/* 卡片顶部操作区 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;
  gap: 16px;
}

.header-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.section-description {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

.add-user-btn {
  background: var(--primary-blue);
  border: none;
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
  transition: var(--transition);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
}

.add-user-btn:hover {
  background: var(--primary-blue-dark);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(52, 152, 219, 0.3);
  color: white;
}

/* 搜索和筛选区域 */
.search-filter {
  display: flex;
  gap: 16px;
  padding: 24px;
  padding-bottom: 0;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 400px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  transition: var(--transition);
}

.search-input:hover {
  border-color: var(--primary-blue-light);
  box-shadow: 0 2px 8px rgba(52, 152, 219, 0.1);
}

.role-filter {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  transition: var(--transition);
}

.role-filter:hover {
  border-color: var(--primary-blue-light);
}

/* 用户列表表格 */
.user-table {
  margin-top: 24px;
  border-radius: 8px;
  overflow: hidden;
  overflow-x: auto;
  width: 100%;
}

.user-table :deep(.el-table__inner-wrapper) {
  border-radius: 8px;
  overflow: hidden;
}

.user-table :deep(.el-table__header-wrapper) {
  background: var(--primary-blue-ultralight);
}

.user-table :deep(.el-table__header th) {
  background: var(--primary-blue-ultralight);
  color: var(--primary-blue-dark);
  font-weight: 600;
  border-bottom: 1px solid #f0f0f0;
  padding: 16px;
}

.user-table :deep(.el-table__body tr) {
  transition: var(--transition);
}

.user-table :deep(.el-table__body tr:hover) {
  background: rgba(52, 152, 219, 0.03);
}

.user-table :deep(.el-table__body td) {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  color: var(--text-primary);
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar-small {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: var(--primary-blue-ultralight);
  color: var(--primary-blue);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.user-name {
  font-weight: 500;
  color: var(--text-primary);
}

/* 角色标签 */
.role-tag {
  padding: 4px 12px;
  font-size: 12px;
  border-radius: 4px;
  transition: var(--transition);
}

/* 操作按钮 */
.operation-btn {
  margin: 0 4px;
  padding: 4px 12px;
  border-radius: 6px;
  transition: var(--transition);
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.operation-btn:hover {
  transform: translateY(-1px);
}

/* 分页组件 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: white;
  border-top: 1px solid #f0f0f0;
}

.pagination-info {
  font-size: 14px;
  color: var(--text-secondary);
}

.highlight-text {
  color: var(--primary-blue);
  font-weight: 600;
  margin: 0 4px;
}

.pagination {
  display: flex;
  align-items: center;
}

.pagination :deep(.el-pagination__item) {
  border-radius: 6px;
  transition: var(--transition);
}

.pagination :deep(.el-pagination__item:hover) {
  color: var(--primary-blue);
  border-color: var(--primary-blue);
}

.pagination :deep(.el-pagination__item.is-active) {
  background: var(--primary-blue);
  border-color: var(--primary-blue);
  color: white;
}

/* 用户对话框 */
.user-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-blue-dark) 100%);
  color: white;
  border-radius: var(--border-radius) var(--border-radius) 0 0;
  padding: 20px 24px;
}

.user-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.user-dialog :deep(.el-dialog__body) {
  padding: 24px;
  background: white;
}

.user-dialog :deep(.el-dialog__footer) {
  padding: 16px 24px;
  background: #f8f9fa;
  border-top: 1px solid #f0f0f0;
  border-radius: 0 0 var(--border-radius) var(--border-radius);
}

/* 表单样式 */
.user-form {
  margin-bottom: 8px;
}

.form-input {
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  transition: var(--transition);
}

.form-input:hover {
  border-color: var(--primary-blue-light);
}

.form-input:focus {
  border-color: var(--primary-blue);
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.1);
}

.form-select {
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  transition: var(--transition);
}

.form-select:hover {
  border-color: var(--primary-blue-light);
}

.form-select:focus {
  border-color: var(--primary-blue);
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.1);
}

.form-checkbox {
  margin-right: 16px;
  color: var(--text-primary);
}

.form-checkbox :deep(.el-checkbox__label) {
  color: var(--text-primary);
}

/* 按钮样式 */
.export-excel-btn {
  margin-left: 8px;
}

/* 对话框按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn {
  padding: 8px 20px;
  border-radius: 6px;
  transition: var(--transition);
}

.confirm-btn {
  padding: 8px 20px;
  border-radius: 6px;
  background: var(--primary-blue);
  border: none;
  transition: var(--transition);
}

.confirm-btn:hover {
  background: var(--primary-blue-dark);
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management-container {
    padding: 12px;
    gap: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .page-header h2 {
    font-size: 1.5rem;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    padding: 16px;
  }
  
  .section-title {
    font-size: 1.25rem;
  }
  
  .search-filter {
    flex-direction: column;
    align-items: stretch;
    padding: 16px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .role-filter {
    width: 100%;
  }
  
  .user-table :deep(.el-table__header th),
  .user-table :deep(.el-table__body td) {
    padding: 12px 8px;
    font-size: 14px;
  }
  
  .pagination-container {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
    padding: 16px;
  }
  
  .user-dialog :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 auto;
  }
}
</style>